<template>
    <view class="component">
        <view class="kaiItemWrap bg-fff onlyOneKaiSty" v-show="kaiDetail && kaiDetail.allTypes">
            <view class="titleWrap flex">
                <view class="title font15 fontBold right-5">一房一价分析表</view>
                <view class="kaiGroup">
		            <up-tabs :list="kaiAverageList" keyName="title" :current="currKai" lineColor="#007235" @click="changeTabs"></up-tabs>
                </view>
            </view>

            <view class="typePriceNavs flex bg-theme-opacity text-center top-20 font13" v-if="kaiDetail.building_list">
                <view class="selBuilBtn border-theme bg-fff font12">
                    <view class="selBtn flex col-theme" @click="clickSelBtn">
                        <text class="right-5">{{ kaiDetail.building_list[buildCurrArr[currKai]] }}</text>
                        <u-icon :name="showOptions?'arrow-up-fill':'arrow-down-fill'" color="#007235" size="10"></u-icon>
                    </view>
                    
                    <view class="selWrap text-center bg-fff shadow" v-show="showOptions">
                        <view 
                            v-for="(buildingItem, buildI) in filteredBuildingList" 
                            :key="buildI"
                            class="selItem"
                            :class="{'col-theme': buildCurrArr[currKai] === buildI, 'col-3e': buildCurrArr[currKai] !== buildI}"
                            @click="changeBuilding(buildI)"
                        >
                            {{ buildingItem }}
                        </view>
                    </view>
                </view>
                <view class="selBuilBtn border-theme bg-fff font12">
                    <view class="selBtn flex col-theme" @click="clickTypeSelBtn">
                        <text class="right-5">{{ kaiDetail.typesList[typeCurrArr[currKai]] }}</text>
                        <u-icon :name="showTypeOpts?'arrow-up-fill':'arrow-down-fill'" color="#007235" size="10"></u-icon>
                    </view>
                    
                    <view class="selWrap text-center bg-fff shadow" v-if="showTypeOpts">
                        <block v-for="(typeItem, typeI) in kaiDetail.typesList" :key="typeI">
                            <view class="selItem" :class="typeCurrArr[currKai] === typeI ?'col-theme':'col-3e'" @click="changeType(typeI)">{{ typeItem }}</view>
                        </block>
                    </view>
                </view>
                <view class="font12">
                    <view class="navPriceItem">
                        <text class="fontBold">{{ kaiDetail.price_avg || '--' }}</text><text class="font12">元/m²</text>
                    </view>
                    <view class="top-5">套均单价</view>
                </view>

                <view class="font12">
                    <view class="navPriceItem">
                        <text class="fontBold">{{ kaiDetail.amount_avg || '--' }}</text><text class="font12">万</text>
                    </view>
                    <view class="top-5">套均总价</view>
                </view>

                <view class="font12">
                    <view class="navPriceItem">
                        <text class="fontBold">{{ kaiDetail.count || '--' }}</text><text class="font12">套</text>
                    </view>
                    <view class="top-5" v-if="buildCurrArr[currKai] !== 0 || typeCurrArr[currKai] !== 0">
                        {{ buildCurrArr[currKai] !== 0 ? kaiDetail.building_list[buildCurrArr[currKai]] : '' }} {{ typeCurrArr[currKai] !== 0 ? kaiDetail.typesList[typeCurrArr[currKai]] : '' }}
                    </view>
                    <view class="top-5" v-else>本期套数</view>
                </view>
            </view>

            <view class="houseListWrap">
                <block v-if="kaiDetail.allTypes && kaiDetail.allTypes.length > 0">
                    <view class="typeGroupWrap">
                        <view class="itemRow flex top-10 font12" v-for="(item,index) in kaiDetail.allTypes" :key="index">
                            <view class="houseTypeTxt flex" @click="toEvaluationDetail(kaiDetail.pan_id, item.eid)">
                                <view class="buildItem">{{ item.buildName.substr(0,3) }}</view>
                                <view class="typeItem">{{ item.title.substr(0,2) }}</view>
                                <view class="sizeItem left-3 txtHidden">
                                    <block v-if="item.size"><text class="font10">约</text>{{ item.size }}m²</block>
                                    <block v-else>--</block>
                                </view>
                            </view>
                            <view class="arrowWrap">
                                <u-icon name="arrow-right" color="#333333" size="10"></u-icon>
                            </view>
                            <view class="houseAmountTxt txtHidden">
                                <block v-if="item.amount_min.amount">
                                    <text class="font10">约</text>{{ toFixedStr(item.amount_min.amount) }}-{{ toFixedStr(item.amount_max.amount) }}万
                                </block>
                                <text v-else>总价待定</text>
                            </view>
                            <view class="progrCount flex">
                                <view class="progress">
                                    <u-line-progress :round="false" activeColor="#007235" :percentage="calcRatio(item, kaiDetail.house_count)" :showText="false" height="9"></u-line-progress>
                                </view>
                                <view class="count text-right">{{ item.count }}套</view>
                            </view>
                        </view>
                    </view>
                    
                    <view class="comBody top-20">
                        <view class="tableWrap">
                            <view class="rowWrap flex bg-F1F1F1 text-center font12">
                                <view class="itemWrap item2">
                                    户型
                                </view>
                                <view class="itemWrap item3">
                                    平均单价<text class="font9">元/m²</text>
                                </view>
                                <view class="itemWrap item4">
                                    最低单价<text class="font9">元/m²</text>
                                </view>
                                <view class="itemWrap item5">
                                    最高单价<text class="font9">元/m²</text>
                                </view>
                            </view>

                            <block v-for="(colItem, colIndex) in kaiDetail.allTypes" :key="colIndex">
                                <view class="rowWrap flex font12">
                                    <view class="itemWrap item2 text-left">
                                        <view class="txtHidden">
                                            <text class="buildName">{{ colItem.buildName.substr(0,3) }}</text>
                                            <text>{{ colItem.title }}</text>
                                            <text class="left-3">{{colItem.size?'约'+colItem.size+'m²':'--'}}</text>
                                        </view>
                                    </view>
                                    <view class="itemWrap item3 text-center">
                                        {{colItem.price_avg?colItem.price_avg:'--'}}
                                    </view>
                                    <view class="itemWrap item4 col-316aff text-center">
                                        {{colItem.price_min.price?colItem.price_min.price:'--'}}
                                    </view>
                                    
                                    <view class="itemWrap item5 col-fd0100 text-center">
                                        {{colItem.price_max.price?colItem.price_max.price:'--'}}
                                    </view>
                                </view>
                            </block>
                        </view>
                    </view>
                </block>
                <up-empty text="暂无数据" mode="list" marginTop="100" v-if="kaiDetail.allTypes.length === 0"></up-empty>
            </view>
            <view class="selectionBtn font15 fontBold top-20 text-center bg-theme-opacity col-theme" @click="toOneHouseOnePriceTable">
                各楼栋一房一价分析
            </view>
        </view>
    </view>
</template>
<script>
    import { delSameObjValue } from '@/common/common';
	export default {
		data() {
			return {
                currKai: 0,
                _cache: {},
                buildIndex: 0,
                buildCurrArr: [],
                typeCurrArr: [],
                kaiAverageList: [],
                showOptions: false,
                showTypeOpts: false
            };
		},
		props: {
            list: {
                type: Array,
                default: () => ([])
            },
            product: {
                type: Object,
                default: () => ({})
            },
            kaiId: {
                type: Number || String,
                default: ''
            }
		},
        created() {
            let kaiList = this.list.filter(item => (item.building_data_list && item.building_data_list.length > 0));
            kaiList.forEach((kaiItem, index) => {
                const buildLeng = kaiItem.building_data_list.length;
                let houseTypeArr = [];
                let typesArr = [];
                if(kaiItem.building_data_list && buildLeng> 0) {
                    kaiItem.building_data_list.forEach(buildItem => {
                        //开盘内所有楼栋内的户型集合再一起,户型内新增buildName属性
                        buildItem.list.forEach(houseItem => {
                            houseItem.buildName = buildItem.title;
                            typesArr.push(houseItem)
                        })
                        //所有户型交集
                        houseTypeArr.push(...(buildItem.list.map(typeItem => typeItem.title)));
                    })
                    //再根据条件去重
                    let filtTypesList = delSameObjValue(typesArr, 'resultNum', ['title','size', 'buildName'], ['count']);
                    kaiItem.building_list = ['选楼栋', ...Array.from(new Set(kaiItem.building_list)).sort()];
                    kaiItem.allTypes = filtTypesList.map(item => ({...item, count: item.resultNum}));
                    kaiItem.typesList = ['选户型', ...Array.from(new Set(houseTypeArr)).sort()];
                    this.buildCurrArr[index] = 0;
                    this.typeCurrArr[index] = 0;
                    houseTypeArr = [];
                    typesArr = [];
                }
            })
            
            this.kaiAverageList = Object.freeze(kaiList);
            kaiList = [];
        },
        computed:{
            kaiDetail() {
                // 添加缓存机制
                const cacheKey = `${this.currKai}-${this.buildCurrArr[this.currKai]}-${this.typeCurrArr[this.currKai]}`;
                if (this._cache?.[cacheKey]) {
                    return this._cache[cacheKey];
                }

                if (this.kaiAverageList.length === 0) return {};
                
                // 避免深拷贝整个列表，只拷贝需要的部分
                const currentKai = this.kaiAverageList[this.currKai];
                if (!currentKai) return {};

                const buildOptI = this.buildCurrArr[this.currKai];
                const typeOptI = this.typeCurrArr[this.currKai];
                const currBuildName = currentKai.building_list?.[buildOptI];
                const currTypeName = currentKai.typesList?.[typeOptI];
                
                // 使用computed处理数据过滤
                let allHouseList = this.filterHouseList(currentKai.allTypes, currBuildName, currTypeName);
                
                // 计算统计数据
                const stats = this.calculateStats(allHouseList, currBuildName, currTypeName, currentKai);
                
                const result = {
                    ...stats,
                    allTypes: allHouseList,
                    building_list: currentKai.building_list,
                    typesList: currentKai.typesList,
                    pan_id: currentKai.pan_id
                };
                
                // 缓存结果
                if (!this._cache) this._cache = {};
                this._cache[cacheKey] = result;
                
                return result;
            },

            // 优化楼栋列表过滤
            filteredBuildingList() {
                return this.kaiDetail?.building_list || [];
            }
        },

        //组件销毁
        beforeDestroy() {
            // 组件销毁前清理缓存
            this.clearCache();
        },

		methods: {
            // 抽离过滤逻辑为独立方法
            filterHouseList(allTypes, buildName, typeName) {
                if (!allTypes) return [];
                
                let filtered = [...allTypes];
                
                if (buildName !== '选楼栋') {
                    filtered = filtered.filter(item => item.buildName === buildName);
                }
                
                if (typeName !== '选户型') {
                    filtered = filtered.filter(item => item.title === typeName);
                }
                
                return filtered;
            },

            // 抽离统计计算逻辑
            calculateStats(houseList, buildName, typeName, currentKai) {
                if (buildName === '选楼栋' && typeName === '选户型') {
                    return {
                        amount_avg: currentKai.amount_avg.toFixed(0),
                        price_avg: currentKai.price_avg.toFixed(0),
                        count: currentKai.house_count
                    };
                }

                const stats = houseList.reduce((acc, item) => {
                    acc.count += item.count;
                    acc.totalPrice += item.price_avg;
                    acc.totalAmount += item.amount_avg;
                    return acc;
                }, { count: 0, totalPrice: 0, totalAmount: 0 });

                const len = houseList.length;
                return {
                    amount_avg: (stats.totalAmount / len).toFixed(0),
                    price_avg: (stats.totalPrice / len).toFixed(0),
                    count: stats.count
                };
            },

            // 优化事件处理器
            changeTabs({index}) {
                uni.$u.debounce(() => {
                    if(this.currKai === index) return;
                    this.showOptions = false;
                    this.showTypeOpts = false;
                    this.currKai = index;
                }, 500)
            },

            // 清除缓存的辅助方法
            clearCache() {
                this._cache = null;
            },

            //计算房源中户型比例
            calcRatio(info, total) {
                if(info.count) {
                    return (info.count / total).toFixed(1)
                }
                return 0
            },

            //字符串转化为数字,再截取小数点
            toFixedStr(str) {
                return parseFloat(str).toFixed(0)
            },

            //点击本期全部按钮
            clickSelBtn() {
                this.showOptions = !this.showOptions;
                this.showTypeOpts = false;
            },

            //点击选择户型按钮显示opts
            clickTypeSelBtn() {
                this.showTypeOpts = !this.showTypeOpts;
                this.showOptions = false;
            },

            //切换开盘内的楼栋
            changeBuilding(buildI) {
                //先让户型重置
                this.typeCurrArr.splice(this.currKai, 1, 0);
                this.buildCurrArr.splice(this.currKai, 1, buildI);
                this.showOptions = false;
                this.showTypeOpts = false;
            },

            //切换户型
            changeType(typeI) {
                this.typeCurrArr.splice(this.currKai, 1, typeI);
                this.showOptions = false;
                this.showTypeOpts = false;
            },

            //跳转一房一价分析表页面
            toOneHouseOnePriceTable(){
                uni.navigateTo({
                    // url: `/pages/product/one-house-one-price/one-house-one-price-table?productId=${this.product.id}&kaiId=${this.kaiId}&title=${this.product.id}`
                    url: `/pages/product/one-house-one-price/one-house-one-price-column-average?productId=${this.product.id}&kaiId=${this.kaiId}&title=${this.product.title}`
                })
            },

            //跳转户型评测详情
            // toEvaluationDetail(kaiId='', typeId='') {
            //     if(!typeId) return;
            //     uni.navigateTo({
            //     	url: `/pages/house/house-type/detail/page?productId=${this.product.id}&sizeId=${typeId}&kaiId=${kaiId}`
            //     })
            // }
		}
	}
    
</script>

<style scoped lang="scss">
.component{
    .kaiItemWrap{
        padding: 30rpx 22rpx;
        .titleWrap{
            justify-content: flex-start;
            .title{
                width: 240rpx;
                border-right: 2rpx solid rgba(0,0,0,.1);
            }
            .kaiGroup{
                width: calc(100% - 242rpx);
            }
        }
    }
    .onlyOneKaiSty{
    }
    .typePriceNavs{
        padding: 28rpx 20rpx;
        justify-content: space-between;
        border-top: 1rpx solid rgba(250, 160, 0, 0.1);
        border-left: 1rpx solid rgba(250, 160, 0, 0.1);
        border-right: 1rpx solid rgba(250, 160, 0, 0.1);
        .selBuilBtn{
            width: 116rpx;
            position: relative;
            .selBtn{
                height: 50rpx;
            }
            .selWrap{
                position: absolute;
                width: 116rpx;
                max-height: 360rpx;
                overflow-y: scroll;
                top: 54rpx;
                left: 0;
                z-index: 10;
                border-radius: 10rpx;
                .selItem{
                    height: 60rpx;
                    line-height: 60rpx;
                    border-bottom: 1rpx solid rgba(0,0,0,.1);
                }
            }
        }
    }
    .houseListWrap{
        min-height: 260rpx;
        .typeGroupWrap{
            padding: 10rpx 20rpx 30rpx 20rpx;
            border-left: 1rpx solid rgba(0,0,0,.06);
            border-right: 1rpx solid rgba(0,0,0,.06);
            border-bottom: 1rpx solid rgba(0,0,0,.06);
        }
    }
    
    .itemRow{
        justify-content: space-between;
        .houseTypeTxt{
            justify-content: flex-start;
            width: 35%;
            .buildItem{
                width: 50rpx;
            }
            .sizeItem{
                max-width: 80%;
            }
        }
        .arrowWrap{
            width: 40rpx;
        }
        .houseAmountTxt{
            width: 35%;
        }
        .progrCount{
            width: calc(50% - 40rpx);
            justify-content: space-between;
            .progress{
                width: calc(100% - 70rpx);
            }
            .count{
                width: 70rpx;
            }
        }
    }
    .comBody{
        .tableWrap{
            border-bottom: 2rpx solid rgba(0,0,0,.06);
            border-left: 2rpx solid rgba(0,0,0,.06);
            border-right: 2rpx solid rgba(0,0,0,.06);
            .rowWrap{
                align-items: stretch;
                border-bottom: 2rpx solid rgba(0,0,0,.06);
                &:last-child{
                    border: none;
                }
                .itemWrap{
                    padding: 15rpx 0;
                }
                .item2{
                    width: 31%;
                    padding-left: 20rpx;
                    .buildName{
                        width: 50rpx;
                        display: inline-block;
                    }
                }
                .item3{
                    width: 23%;
                }
                .item4,.item5{
                    width: 23%;
                }
            }
        }
    }
    .selectionBtn{
        height: 70rpx;
        line-height: 70rpx;
        border-radius: 10rpx;
    }
}
</style>